import { useRouter } from "next/router";
import { connect } from "react-redux";
import { useEffect } from "react";
import { getCustomerList } from '@/store/actions/cart';
// 样式
import styles from '@/styles/ShoppingCart.module.scss';
// 组价
import Breadcrumb from '@/components/Breadcrumb';
import OrderList from '@/pages_components/shopping_cart/OrderList';
import OrderSettle from '@/pages_components/shopping_cart/OrderSettle';
import OrderForm from '@/pages_components/shopping_cart/OrderForm';
import Coupon from '@/pages_components/shopping_cart/Coupon';

// 清除
function clearStorageData (router){
    const dataList = JSON.parse(sessionStorage.getItem('cartList') || '[]');
    if(!dataList?.length){
        router.replace('/shopping_cart/');
        return false
    }
    dataList.forEach(item => {
        const { goodsCartActivityListDTO } = item;
        goodsCartActivityListDTO.forEach(dto => {
            delete dto.customersList;
        })
    });
    sessionStorage.setItem('cartList', JSON.stringify(dataList));
    sessionStorage.removeItem('useCoupon');
    sessionStorage.removeItem('contact');
}

const CartOrder = ({ _getCustomerList }) => {

    const router = useRouter();

    useEffect(() => {

        _getCustomerList();
        // 重置storage， 若用户刷新页面，则清除优惠券和游客信息
        clearStorageData(router);

        return function (){
            sessionStorage.removeItem('cartList');
        }
    }, []);

    return (
        <div className={styles['shopping-cart-order']}>
            <div className="max-content">
                <Breadcrumb params={
                    [
                        { name: '我的购物车', url: '/shopping_cart/' },
                        { name: '购物车结算', url: `/shopping_cart/order/` }
                    ]
                } />
                <section className={styles['content']}>
                    <div className={styles['top']}><span>商品清单</span></div>
                    <OrderList />
                    {/* 出行人 */}
                    <OrderForm />
                    {/* 优惠券 */}
                    <Coupon />
                    {/* 去付款 */}
                    <OrderSettle />
                </section>
            </div>
        </div>
    )
}

const mapDispatchToProps = dispatch => {
    return {
        _getCustomerList: v => dispatch(getCustomerList(v))
    }
}
export default connect(null, mapDispatchToProps)(CartOrder)